﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace XTYAPI.通讯.WebSokcet
{
    /// <summary>
    /// WebSocket客户端
    /// </summary>
    public class WebSocketClient
    {
        public event Action<string> ClientEvent;
        ClientWebSocket socket;
        public bool Connectd { get; set; }
        /// <summary>
        /// 开始连接服务器 ws:websokcet的意思
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        public async Task Start(string uri= "ws://localhost:8080/")
        {
            try
            {
                socket = new ClientWebSocket();
                await socket.ConnectAsync(new Uri(uri), CancellationToken.None);
                ClientEvent?.Invoke("连接到服务器....");
                Connectd = true;
                var responseBuffer = new byte[1024];
                while (true)
                {
                    //Console.Write("输入发送消息: ");
                    //ClientEvent?.Invoke("输入发送消息:");
                    //var message = "hello";
                    //var buffer = Encoding.UTF8.GetBytes(message);
                    //await socket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);                
                    var result = await socket.ReceiveAsync(new ArraySegment<byte>(responseBuffer), CancellationToken.None);
                    var response = Encoding.UTF8.GetString(responseBuffer, 0, result.Count);
                    ClientEvent.Invoke($"来自服务器数据：{response}");
                }
            }
            catch (Exception ex)
            {
                ClientEvent?.Invoke("连接到服务器失败....");
                ClientEvent?.Invoke(ex.ToString());
                Connectd = false;
                return;
            }
        }
        /// <summary>
        /// 给服务器发消息
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public async Task SendServer(string str)
        {
            if (socket == null)
            {
                ClientEvent?.Invoke("webSocekt服务器还没连上：" + str);
                return;
            }
            if (!string.IsNullOrEmpty(str))
            {
                var response = Encoding.UTF8.GetBytes(str);
                ClientEvent?.Invoke(str);
                await socket?.SendAsync(new ArraySegment<byte>(response), WebSocketMessageType.Text, true, CancellationToken.None);
            }
        }
    }
}
